package com.birdboot.core;

import com.birdboot.http.HttpServletRequest;

import java.io.*;
import java.net.Socket;
import java.net.URISyntaxException;
import java.nio.charset.StandardCharsets;

public class ClientHandler implements Runnable{
    private Socket socket;

    public ClientHandler(Socket socket) {
        this.socket = socket;
    }

    public void run() {
        HttpServletRequest request = null;
        try {
            request = new HttpServletRequest(socket);
            String path = request.getUri();
            System.out.println("抽象路径:" + path);

            File baseDir = new File(
                    ClientHandler.class.getClassLoader().getResource(".").toURI()
            );
            File staticDir = new File(baseDir, "static");
            File file = new File(staticDir, "Index.html");
            OutputStream out = socket.getOutputStream();
            //1发送状态行
            String line = "HTTP/1.1 200 OK";
            out.write(line.getBytes(StandardCharsets.ISO_8859_1));
            out.write(13);//单独发送回车符
            out.write(10);//单独发送换行符
            //2发送响应头
            line = "Content-Type: text/html";
            out.write(line.getBytes(StandardCharsets.ISO_8859_1));
            out.write(13);//单独发送回车符
            out.write(10);//单独发送换行符
            line = "Content-Length: " + file.length();
            out.write(line.getBytes(StandardCharsets.ISO_8859_1));
            out.write(13);//单独发送回车符
            out.write(10);//单独发送换行符
            //单独发送回车+换行表达响应头发完了
            out.write(13);//单独发送回车符
            out.write(10);//单独发送换行符

            //3发送响应正文(index.html页面内容发送出去)
            FileInputStream fis = new FileInputStream(file);
            byte[] data = new byte[1024 * 10];
            int len;
            while ((len = fis.read(data)) != -1) {
                out.write(data, 0, len);
            }
        } catch (IOException | URISyntaxException e) {
            e.printStackTrace();
        } finally {
            //遵循HTTP协议要求,一问一答后与客户端断开连接
            try {
                socket.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}
